'use strict';

const BaseController = require('./base');

class UserController extends BaseController {
  get _service() {
    return 'user';
  }

  async jwtSign(id) {
    const { ctx, app } = this;
    const username = ctx.params('userName');
    // 将用户id和用户名转换成token
    const token = app.jwt.sign({
      username,
      id,
    }, app.config.jwt.secret);
    // redis存储token信息 格式为 终端+用户id：token
    await app.redis.set(ctx.deviceType + id, token, 'EX', app.config.redisExpire);
    return token;
  }

  async login() {
    const { ctx } = this;
    const { userName, password } = ctx.params();
    const user = await this._getService().findOne({ userName, password });
    if (!user) {
      this.error('用户不存在或者密码错误');
      return;
    }
    const token = await this.jwtSign(user.id);
    const tempMenus = await ctx.service.menu.findAll({ auth: user.userAndRole.role.auth, type: ctx.deviceType });
    const menus = ctx.helper.convert(JSON.parse(JSON.stringify(tempMenus)).map(item => {
      const temp = { id: item.id, text: item.name, url: item.href, parentId: item.parentId };
      if (item.children && item.children.length) {
        temp.children = item.children;
      }
      return temp;
    }));
    this.success({
      user,
      menus,
      token,
    });
  }

  async create() {
    const { ctx } = this;
    const { userName, password, nickName } = ctx.params();
    const user = await this._getService().findOne({ userName });
    if (user) {
      this.error('用户已经存在');
      return;
    }
    const newUser = await this._getService().create({
      userName,
      password,
      nickName,
    });
    await ctx.service.userInfo.create({ uid: newUser.id });
    await ctx.service.userAndRole.create({ uid: newUser.id, rid: 1 });
    await ctx.service.userRelation.create({ uid: newUser.id, followId: newUser.id });
    if (newUser) {
      this.success();
      return;
    }
    this.error('注册用户失败');
  }

  async show() {
    const { ctx } = this;
    const { id } = ctx.params;
    const result = await this._getService().findOne({ id });
    if (result) {
      this.success(result);
    } else {
      this.error('获取信息失败');
    }
  }

  async update() {
    const { ctx } = this;
    const { oldPassword, newPassword, nickName } = ctx.params();
    const { id } = ctx.params;
    if (oldPassword !== newPassword) {
      this.error('前后密码不一致');
      return;
    }
    const password = newPassword;
    const result = await this._getService().update({ password, nickName, id });
    if (result) {
      this.success();
    } else {
      this.error('更新用户失败');
    }
  }

  async checkToken() {
    const { ctx } = this;
    const user = await this._getService().findOne({ userName: ctx.username, id: ctx.userId });
    const tempMenus = await ctx.service.menu.findAll({ auth: user.userAndRole.role.auth, type: ctx.deviceType });
    const menus = ctx.helper.convert(JSON.parse(JSON.stringify(tempMenus)).map(item => {
      const temp = { id: item.id, text: item.name, url: item.href, parentId: item.parentId };
      if (item.children && item.children.length) {
        temp.children = item.children;
      }
      return temp;
    }));
    this.success({
      user,
      menus,
      token: ctx.request.header.token,
    });
  }

  async logout() {
    const { ctx } = this;
    await ctx.app.redis.del(ctx.deviceType + ctx.userId);
    this.success();
  }

  async index() {
    const { ctx } = this;
    const { userName, nickName, rid, prop, sort, pageIndex, pageSize } = ctx.params();
    const { createdAt } = ctx.queries;
    const result = await this._getService().findList({ userName, nickName, rid, prop, sort, pageIndex, pageSize, createdAt });
    if (result) {
      this.success(result.data, result.count);
    } else {
      this.error('获取用户信息失败');
    }
  }

  async statisticalUser() {
    const { ctx } = this;
    const { startTime, areaId } = ctx.params();
    const result = await this._getService().statisticalUser({ startTime, areaId });
    if (result && result[0]) {
      this.success(Object.entries(result[0]).map(item => ({ key: item[0] + '月', value: +item[1] })));
    } else {
      this.error('获取用户失败');
    }
  }
}

module.exports = UserController;
